<?php
namespace app\controller\simManager;

use app\exception\ErrnoPlus;
use share\service\cache\CommonCacheKeyService;
use share\controller\ApiBaseController;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\RedisService;
use share\utils\Helper;
use think\response\Json;

class WebSimBossController extends ApiBaseController{

    CONST LOGIN_TOKEN_TIMEOUT = 1800;

    protected $beforeActionList = [
        "checkUser",
    ];

    protected $_userInfo = null;

    
    /**
     * @param array $data
     * @return \think\response\Json
     */
    public static function json_out($data,$isLog = true){         
        return new Json($data);
    }

    /**
     * @return \think\response\Json
     */
    public static function ok($data = [],$msg = 'success',$code = 0){
        $resp = [
            'resultCode' => $code ,
            'errorString' => $msg,
        ];
        if($data){
            $resp['body'] = $data;
        }
        return self::json_out($resp);
    }

    /**
     * @return \think\response\Json
     */
    public static function fail( $msg, $code = Errno::COMMON_UNKNOWN, $data = []){
        $resp = [
            'resultCode' => $code,
            'errorString' => $msg,
        ];
        if($data){
            $resp['body'] = $data;
        }
        return self::json_out($resp);
    }
 

    /**
     * 获取aes 加密对象数据
     */
    public function getAESDecodeData($keyIndex ='key',$dataIndex = 'smData'){
        $input = $this->request->param();
        if(!isset($input[$keyIndex]) || !isset($input[$dataIndex])){
            throw new ApiException("lost data",ErrnoPlus::PARAM_ERROR);
        }
        $iv = config("AES_IV");        
        $key = $input[$keyIndex];
        return self::decodeAESData($key,$iv,$input[$dataIndex]);       
    }

    public static function decodeAESData($key,$iv,$data){
        $key = substr($key,0,16);
        if(strlen($key) < 16){
            $key = str_pad($key,16,'0',STR_PAD_RIGHT);
        }
        $binData = hex2bin($data);
        if($binData === false){
            throw new ApiException("smData error",ErrnoPlus::PARAM_ERROR);
        }        
        $rawString = Helper::aesDecrypt(base64_encode($binData),$key,$iv);
        if(!$rawString){
            throw new ApiException("smData descrypt error",ErrnoPlus::PARAM_ERROR);
        }
        $rawData = @json_decode($rawString,true);
        return $rawData;
    }

    public static function authToken($userInfo){
        $token = Helper::getUnique();
        $key = self::getAuthCacheKey($token);
        RedisService::instance(RedisService::CACHE_DB_BASE)->setJson($key,$userInfo,self::LOGIN_TOKEN_TIMEOUT);
        return $token;
    }

    public static function getAuthInfoByToken($token){
        $key = self::getAuthCacheKey($token);
        return RedisService::instance(RedisService::CACHE_DB_BASE)->getJson($key);
    }

    public static function getAuthCacheKey($token){
        return CommonCacheKeyService::getCacheKey(CommonCacheKeyService::CACHE_KEY_LOGIN_SIM_BOSS_ADMIN ,['token' =>md5($token)]);
    }


    /**
     * 检查已登录用户
     */
    public function checkUser(){
      
        $token = $this->request->header('token');
        if(empty($token)){
            throw new ApiException("当前用户未登录",ErrnoPlus::WEB_LOGOUT);
        }   
        $userInfo = self::getAuthInfoByToken($token);
        if(empty($userInfo)){
            throw new ApiException("当前用户登录信息已过期,请重新登录",ErrnoPlus::WEB_LOGOUT);
        }
        $this->_userInfo  = $userInfo;
        $cacheKey = self::getAuthCacheKey($token);
        RedisService::instance(RedisService::CACHE_DB_BASE)->expire($cacheKey,self::LOGIN_TOKEN_TIMEOUT);
        return ;
       
    }
}